package com.tanx.controller.init;

import com.tanx.dto.init.InitFormDto;
import com.tanx.service.InitAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * 负责系统初始化,主要是初始化管理员账号密码等
 * Created by 唐旭 on 2015/10/10.
 */
@Controller
@RequestMapping("init")
public class InitController {

    @Autowired
    private InitAdminService service;

    @RequestMapping("/form.htm")
    public String initForm(Model model) {
        if (service.checkNotUsers()) {
            model.addAttribute("formDto", new InitFormDto());
            return "init/form";
        } else {
            return "redirect:/404.htm";
        }
    }

    @RequestMapping(value = "/form.htm", method = RequestMethod.POST)
    public String postForm(@ModelAttribute("formDto") @Valid InitFormDto formDto,
                           BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "init/form";
        }
        service.initApplication(formDto);
        return "redirect:/index.htm";
    }
}
